import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import org.jibble.pircbot.*;

/**
 * BOTOVA CLASSA
 * 
 * @author harph je gej
 * 
 */
public class Shalatik extends PircBot {
	ArrayList<String> noobs;
	Connection con;
	DatabaseConnect dc;

	float strkoef1, strkoef2, intkoef1, intkoef2, agikoef1, agikoef2, hpkoef, manakoef;
	float strstaminakoef, intstaminakoef, agistaminakoef, stamina_attack;
	
	public Shalatik(Connection con, String nick, float strkoef1, float strkoef2, float intkoef1, float intkoef2,
			float agikoef1, float agikoef2, float hpkoef, float manakoef, float strstaminakoef,
			float intstaminakoef, float agistaminakoef, float stamina_attack) {
		this.setName(nick);
		this.setAutoNickChange(true);
		this.setLogin("salat");
		noobs = new ArrayList<String>();
		this.con = con;
		setMessageDelay(100);
		dc = new DatabaseConnect(con);
	
		updateDatabase();

		this.strkoef1 = strkoef1;
		this.strkoef2 = strkoef2;
		this.intkoef1 = intkoef1;
		this.intkoef2 = intkoef2;
		this.agikoef1 = agikoef1;
		this.agikoef2 = agikoef2;
		this.hpkoef = hpkoef;
		this.manakoef = manakoef;
		this.strstaminakoef = strstaminakoef;
		this.agistaminakoef = agistaminakoef;
		this.intstaminakoef = intstaminakoef;
		this.stamina_attack = stamina_attack;
	}
	
	void updateDatabase()
	{
		try
		{
			String query = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'shalatikDB' AND TABLE_NAME = 'irc_qog' AND COLUMN_NAME IN ('hp', 'mana', 'class', 'stamina', 'xp')";
			ResultSet rs = dc.sendQuery(query);
			
			ArrayList<String> existingColumns = new ArrayList<String>();
			
			while (rs.next())
			{
				existingColumns.add(rs.getString("COLUMN_NAME"));
			}
			
			ArrayList<HashMap<String, String>> columnsToCreate = new ArrayList<HashMap<String,String>>();
			
			HashMap<String, String> hpColumn = new HashMap<String, String>();
			HashMap<String, String> manaColumn = new HashMap<String, String>();
			HashMap<String, String> classColumn = new HashMap<String, String>();
			HashMap<String, String> staminaColumn = new HashMap<String, String>();
			HashMap<String, String> xpColumn = new HashMap<String, String>();
			
			hpColumn.put("name", "hp");
			hpColumn.put("type", "INT(11)");
			hpColumn.put("default", "0");
			
			columnsToCreate.add(hpColumn);
			
			manaColumn.put("name", "mana");
			manaColumn.put("type", "INT(11)");
			manaColumn.put("default", "0");
			
			columnsToCreate.add(manaColumn);
			
			classColumn.put("name", "class");
			classColumn.put("type", "VARCHAR(3)");
			classColumn.put("default", "''");
			
			columnsToCreate.add(classColumn);
			
			staminaColumn.put("name", "stamina");
			staminaColumn.put("type", "FLOAT(11)");
			staminaColumn.put("default", "0.0");
			
			columnsToCreate.add(staminaColumn);
			
			xpColumn.put("name", "xp");
			xpColumn.put("type", "INT(11)");
			xpColumn.put("default", "0");
			
			columnsToCreate.add(xpColumn);

			for (HashMap<String, String> column : columnsToCreate)
			{
				if (!existingColumns.contains(column.get("name")))
				{
					query = "ALTER TABLE irc_qog ADD COLUMN " + column.get("name") + " " + column.get("type") + " NOT NULL DEFAULT " + column.get("default") + ";";
//					System.out.println(query);
					dc.sendUpdateQuery(query);
				}
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		catch (EOFException e)
		{
			e.printStackTrace();
		}
	}

	boolean checkQOGExists(String user) throws EOFException, SQLException {

		String query = "SELECT id FROM irc_qog WHERE nick = '" + user + "'";
		ResultSet rs = null;

		try {
			rs = dc.sendQuery(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (rs.next()) {
			return true;
		}
		rs.close();
		return false;
	}

	void updateQOG(String user, float value, String channel) {

		String query;

		try {
			if (checkQOGExists(user)) {
				// check if lvlup

				query = "SELECT qog, level, HP, CLASS FROM irc_qog WHERE nick = '"
						+ user + "'";
				ResultSet rs = dc.sendQuery(query);

				if (rs.next()) {
					if (rs.getFloat("qog") + value > 100.0f) {
						query = "UPDATE irc_qog SET qog = "
								+ (rs.getFloat("qog") + value - 100.0f)
								+ ", level = level + 1 WHERE nick = '" + user
								+ "'";
						dc.sendUpdateQuery(query);

						sendMessage(channel, "woot! " + Colors.BOLD + user
								+ Colors.BOLD + " is now level "
								+ (rs.getInt("level") + 1));
					} else {
						query = "UPDATE irc_qog SET qog = qog + " + value
								+ " WHERE nick = '" + user + "'";
						dc.sendUpdateQuery(query);
					}
				}
				rs.close();

			} else {
				query = "INSERT INTO irc_qog VALUES (0, '" + user + "', "
						+ value + ", 1,0,0,'')";
				System.out.println("debug: " + query);
				dc.sendUpdateQuery(query);
			}
		} catch (EOFException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	void pendQOG(String user, float value, String word) throws SQLException {

		String query = "INSERT INTO irc_qog_pending VALUES (0, '" + user
				+ "', " + value + ", '" + word + "', NULL)";

		// System.out.println("debug: "+query);
		dc.sendUpdateQuery(query);
	}

	void qogCalculator(String user, String message) throws IOException,
			NumberFormatException, SQLException {
		File f = new File("qogconfig.cfg");

		FileInputStream cfgread = new FileInputStream(f);
		BufferedReader di = new BufferedReader(new InputStreamReader(cfgread));

		String line;
		String[] sp;
		String key = "";

		while ((line = di.readLine()) != null) {
			sp = line.split(" ");
			key = "";

			for (int i = 0; i < sp.length - 1; i++)
				key += sp[i] + " ";

			key = key.trim();

			if (message.toLowerCase().contains(key)) {
				// updateQOG(user, new Float(sp[sp.length-1]));
				pendQOG(user, new Float(sp[sp.length - 1]), key);
			}
		}

		di.close();
		cfgread.close();
	}

	public void onMessage(String channel, String sender, String login,
			String hostname, String message) {

		if (message.startsWith("!addquote ")) {
			String[] cmds = message.split(" ");

			if (cmds.length > 2) {
				String quota = "";

				for (int i = 1; i < cmds.length - 1; i++) {
					quota += cmds[i] + " ";
				}

				String usr = cmds[cmds.length - 1];
				String query = "INSERT INTO irc_quotes VALUES (0, '" + quota
						+ "', '" + usr + "')";

				try {
					dc.sendUpdateQuery(query);
					sendMessage(channel, "ok citat je tam :>");
				} catch (SQLException e) {
					e.printStackTrace();
					sendMessage(channel, "ech co to nejaka chyba o.O");
				}
			}
		}
		// LEARNZOR
		else if (message.startsWith("!learn ")) {
			String what = "";
			String def = "";
			String[] smes1 = message.split(" = ");

			System.out.println("debug: " + smes1.length);

			if (smes1.length == 2) {
				String[] smes2 = smes1[0].split(" ");
				String[] smes3 = smes1[1].split(" ");

				System.out.println("debug: " + smes3.length);

				if (smes2.length >= 2) {
					for (int i = 1; i < smes2.length; i++)
						what += smes2[i] + " ";

					for (int i = 0; i < smes3.length; i++) {
						def += smes3[i] + " ";
						System.out.println("debug: " + smes3[i]);
					}

					String query = "SELECT ID FROM irc_learn_words where Term = '"
							+ what + "'";

					try {
						ResultSet rs = dc.sendQuery(query);

						int id = 0;

						while (rs.next()) {
							id = rs.getInt("ID");
						}

						if (id == 0) {
							query = "INSERT INTO irc_learn_words VALUES (0, '"
									+ what + "')";
							dc.sendUpdateQuery(query);

							query = "SELECT ID FROM irc_learn_words where Term = '"
									+ what + "'";
							rs = dc.sendQuery(query);

							while (rs.next()) {
								id = rs.getInt("ID");
							}

						}
						rs.close();
						System.out.println("debug: " + def);
						def = def.replace("\\0", "");
						System.out.println("debug: " + def);

						query = "INSERT INTO irc_learn_definitions VALUES ("
								+ id + ", '" + def + "', '" + sender + "')";
						dc.sendUpdateQuery(query);

						sendMessage(channel, "ok definicia pridana :p");

					} catch (SQLException e) {
						e.printStackTrace();
					} catch (EOFException e) {
						System.err
								.println("[error] lost connection with DB, reconnecting");
						try {
							con = DriverManager
									.getConnection("jdbc:mysql://localhost/shalatikDB?user=shalatik&password=Hpp7fF2KySsK52DY");
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							System.out.println("[error] - can't reconnect");
						}
					}

				}
			}
		} else if (message.startsWith("?? ")) {
			String[] smes = message.split(" ");
			String term = "";

			for (int i = 1; i < smes.length; i++)
				term += smes[i] + " ";

			String query = "SELECT ID FROM irc_learn_words WHERE Term = '"
					+ term + "'";

			try {
				ResultSet rs = dc.sendQuery(query);

				int id = 0;

				while (rs.next()) {
					id = rs.getInt("ID");
				}

				if (id != 0) {
					query = "SELECT definition FROM irc_learn_definitions WHERE WID = "
							+ id;
					rs = dc.sendQuery(query);

					String defmessage = "";

					while (rs.next()) {
						defmessage += rs.getString("definition") + "; ";
					}

					sendMessage(channel, Colors.BOLD + term + Colors.BOLD
							+ ": " + defmessage);
				}
				rs.close();

			} catch (SQLException e) {
				e.printStackTrace();
			} catch (EOFException e) {
				System.err
						.println("[error] lost connection with DB, reconnecting");
				try {
					con = DriverManager
							.getConnection("jdbc:mysql://localhost/shalatikDB?user=shalatik&password=Hpp7fF2KySsK52DY");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					System.out.println("[error] - can't reconnect");
				}
			}
		}
		// DANCING, YEAH!
		else if ((message.contains("dance") || message.contains("DANCE"))
				&& !noobs.contains(sender)) {
			sendAction(channel, "dances: :D\\-<");
			sendAction(channel, "dances: :D|-<");
			sendAction(channel, "dances: :D/-<");
			sendAction(channel, "dances: :D|-<");
			sendAction(channel, "dances: :D\\-<");

			noobs.add(sender);
		}
		// ATTACK MODE
		else if (message.startsWith("attack ")) {
			String[] cmds = message.split(" ");

			if (cmds.length > 3 && cmds[2].equalsIgnoreCase("with")) {
				Random generator = new Random();
				String mes = "";
				String who = cmds[1];
				String with = "";
				if (sender.equalsIgnoreCase(who)) {
					sendMessage(channel, "nemozes utocit sam na seba!");
					return;
				}
				boolean jenachane = false;
				for (User u : getUsers(channel)) {
					if (u.getNick().equalsIgnoreCase(who))
						jenachane = true;
				}
				if (!jenachane) {
					sendMessage(channel, "taky tu neni!");
					return;
				}
				for (int i = 3; i < cmds.length; i++) {
					with += cmds[i];

					if (i < cmds.length - 1) {
						with += " ";
					}
				}

				String query = "SELECT id, level, hp, mana, class, stamina, xp FROM irc_qog WHERE nick = '"
						+ sender + "'";

				try {
					ResultSet rs = dc.sendQuery(query);

					int sender_id = 0;
					int sender_level = 0;
					int sender_hp = 0;
					int sender_mana = 0;
					float sender_stamina = 0.0f;
					int sender_xp = 0;
					String sender_class = "";

					while (rs.next()) {
						sender_id = rs.getInt("id");
						sender_level = rs.getInt("level");
						sender_hp = rs.getInt("hp");
						sender_mana = rs.getInt("mana");
						sender_class = rs.getString("class");
						sender_stamina = rs.getFloat("stamina");
						sender_xp = rs.getInt("xp");
					}

					rs.close();
					
					if (sender_stamina < stamina_attack)
					{
						sendMessage(channel, "You don't have enough stamina !");
					}
					else
					{	
						if (sender_id != 0) {
							query = "SELECT id, level, hp, mana, class, stamina, xp FROM irc_qog WHERE nick ='"
									+ who + "'";
							rs = dc.sendQuery(query);
	
							String defmessage = "";
	
							int who_id = 0;
							int who_level = 0;
							int who_hp = 0;
							int who_mana = 0;
							float who_stamina = 0.0f;
							int who_xp = 0;
							String who_class = "";
	
							while (rs.next()) {
								who_id = rs.getInt("id");
								who_level = rs.getInt("level");
								who_hp = rs.getInt("hp");
								who_mana = rs.getInt("mana");
								who_class = rs.getString("class");
								who_stamina = rs.getFloat("stamina");
								who_xp = rs.getInt("xp");
							}
							rs.close();
							if (who_id != 0) {
								if (who_hp <= 0) {
									sendMessage(channel, who + " is already dead !");
								} else {
	
									// CRITICAL!
									int dmgType = generator.nextInt(100);
									double dmgCoef = 0;
	
									if (sender_class.equals("str")) {
										dmgCoef = 3.0f;
									} else if (sender_class.equals("agi")) {
										dmgCoef = 2.5f;
									} else if (sender_class.equals("int")) {
										dmgCoef = 1.5f;
									}
									int base_dmg = (int) (10 + generator
											.nextInt(30) + sender_level
											* (generator.nextInt(3) + 1) * 0.6);
									// 80% chance to attack
									if (dmgType >= 0 && dmgType <= 79) {
										double dmgMax = sender_level * dmgCoef;
										int dmgMaxRound = (int) Math.round(dmgMax);
										int dmg = base_dmg
												+ generator.nextInt(dmgMaxRound)
												+ 1;
	
										int who_new_hp;
	
										if ((who_hp - dmg) <= 0) {
											who_new_hp = 0;
										} else {
											who_new_hp = who_hp - dmg;
										}
	
										query = "UPDATE irc_qog SET hp = "
												+ who_new_hp + " WHERE id ="
												+ who_id;
										dc.sendUpdateQuery(query);
	
										sendMessage(channel, "You hit "
												+ Colors.GREEN + who
												+ Colors.NORMAL + " with " + with
												+ " for " + dmg + " damage.");
	
										if (who_new_hp == 0) {
											sendMessage(channel, "You "
													+ Colors.RED + "KILLED "
													+ Colors.NORMAL + who + " !!");
										}
										
										decreaseStamina(sender, stamina_attack);
									}
									// 5% change to critical
									else if (dmgType >= 80 && dmgType <= 84) {
										double dmgMax = sender_level * dmgCoef;
										int dmgMaxRound = (int) Math.round(dmgMax);
										int dmg = (base_dmg
												+ generator.nextInt(dmgMaxRound) + 1) * 2;
	
										int who_new_hp;
	
										if ((who_hp - dmg) <= 0) {
											who_new_hp = 0;
										} else {
											who_new_hp = who_hp - dmg;
										}
	
										query = "UPDATE irc_qog SET hp = "
												+ who_new_hp + " WHERE id ="
												+ who_id;
										dc.sendUpdateQuery(query);
	
										sendMessage(channel, "You critically hit "
												+ Colors.GREEN + who
												+ Colors.NORMAL + " with " + with
												+ " for " + dmg + " damage !");
	
										if (who_new_hp == 0) {
											sendMessage(channel, "You "
													+ Colors.RED + "KILLED "
													+ Colors.NORMAL + who + " !!");
										}
										
										decreaseStamina(sender, stamina_attack);
									}
									// 10% miss
									else if (dmgType >= 85 && dmgType <= 94) {
										sendMessage(channel, "You missed !");
	
										decreaseStamina(sender, stamina_attack);
									}
									// 5% critical miss
									else if (dmgType >= 95 && dmgType <= 99) {
										double dmgMax = sender_level * dmgCoef
												* 0.5f;
										int dmgMaxRound = (int) Math.round(dmgMax);
										int dmg = base_dmg
												+ generator.nextInt(dmgMaxRound)
												+ 1;
	
										int sender_new_hp;
	
										if ((sender_hp - dmg) <= 0) {
											sender_new_hp = 0;
										} else {
											sender_new_hp = sender_hp - dmg;
										}
	
										query = "UPDATE irc_qog SET hp = "
												+ sender_new_hp + " WHERE id ="
												+ sender_id;
										dc.sendUpdateQuery(query);
	
										sendMessage(channel,
												"You critically missed and hit yourself for "
														+ dmg + " damage !");
	
										if (sender_new_hp == 0) {
											sendMessage(
													channel,
													Colors.RED
															+ "YOU KILLED YOURSELF .. YOU STUPIDO !!"
															+ Colors.NORMAL);
										}
	
										decreaseStamina(sender, stamina_attack);
									}
								}
							}
						}
					}

				} catch (SQLException e) {
					e.printStackTrace();
				} catch (EOFException e) {
					System.err
							.println("[error] lost connection with DB, reconnecting");
					try {
						con = DriverManager
								.getConnection("jdbc:mysql://localhost/shalatikDB?user=shalatik&password=Hpp7fF2KySsK52DY");
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						System.out.println("[error] - can't reconnect");
					}
				}

			} else {
				sendMessage(channel, "[" + Colors.RED + "bad syntax"
						+ Colors.NORMAL + "] attack " + Colors.GREEN + "<who>"
						+ Colors.NORMAL + " with " + Colors.GREEN + "<what>");
			}
		}

		else if (message.equalsIgnoreCase("myinfo")) {
			sendMessage(channel, sender + " tvoje info: " + login + " "
					+ hostname);
		}
		// nastavenie klasy
		else if (message.startsWith("!setclass")) {
			String[] cmds = message.split(" ");
			String query;
			if ((cmds.length > 1)
					&& ((cmds[1].equals("agi") || (cmds[1].equals("str") || (cmds[1]
							.equals("int")))))) {

				query = "select class, level, nick from irc_qog where nick = '"
						+ sender + "'";
				ResultSet rs = null;
				try {
					rs = dc.sendQuery(query);
					if (rs.next()) {
						if (rs.getString("CLASS").equals("agi")
								|| (rs.getString("CLASS").equals("str") || (rs
										.getString("CLASS").equals("int")))) {
							sendMessage(channel, "uz mas klasu nastavenu na: "
									+ rs.getString("CLASS"));
							return;
						}
					} else {
						query = "INSERT INTO irc_qog VALUES (0, '" + sender
								+ "', " + 0 + ", 1,0,0,'')";
						System.out.println("debug: " + query);
						dc.sendUpdateQuery(query);
						query = "select class, level, nick from irc_qog where nick = '"
								+ sender + "'";
						rs = dc.sendQuery(query);
						rs.next();
					}
				} catch (EOFException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					// sendMessage(channel, cmds[1]+": 0.0");
					e.printStackTrace();
				}
				int level = 1;
				try {
					level = rs.getInt("level");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				query = "UPDATE irc_qog SET CLASS =  '" + cmds[1]
						+ "' where nick = '" + sender + "'";
				try {
					dc.sendUpdateQuery(query);
					sendMessage(channel, "nastavujem klasu na: " + cmds[1]);
					if (cmds[1].equals("agi")) {
						query = "UPDATE irc_qog SET HP = " + (agikoef1 * hpkoef * level)
								+ ", mana = " + (agikoef2 * manakoef * level)
								+ ", stamina = " + (15*level)
								+ " WHERE nick = '" + sender + "'";
						dc.sendUpdateQuery(query);
						sendMessage(channel, Colors.GREEN + rs.getString("nick")
								+ Colors.NORMAL + " has spawned!");
					}
					if (cmds[1].equals("int")) {
						query = "UPDATE irc_qog SET HP = "
								+ (intkoef1 * hpkoef * level) + ", mana = "
								+ (intkoef2 * manakoef * level) + ", stamin = "
								+ (10*level) + " WHERE nick = '" + sender + "'";
						dc.sendUpdateQuery(query);
						sendMessage(channel, Colors.GREEN + rs.getString("nick")
								+ Colors.NORMAL + " has spawned!");
					}
					if (cmds[1].equals("str")) {
						query = "UPDATE irc_qog SET HP = " + (strkoef1 * hpkoef * level)
								+ ", mana = " + (strkoef2 * manakoef * level)
								+ ", stamina = " + (10*level)
								+ " WHERE nick = '" + sender + "'";
						dc.sendUpdateQuery(query);
						sendMessage(channel, Colors.GREEN + rs.getString("nick")
								+ Colors.NORMAL + " has spawned!");
					}
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		// halp!!
		else if (message.startsWith("!help")) {
			sendMessage(sender, "irc-dota!");
			sendMessage(
					sender,
					"na zacatie hry si nastav triedu pomocou !setclass trieda, dostupne triedy su agi/int/str, kazda ma iste vyhody aj nevyhody");
			sendMessage(sender, "utocit mozes prikazom attack koho with co");
			sendMessage(sender, "zvysok halpa neskorsejsie :P");
		}
		// vypis statsov
		else if (message.startsWith("!stats") || message.startsWith("!Stats")) {
			String[] cmds = message.split(" ");

			if (cmds.length > 1) {

				String query = "SELECT level, hp, mana, class, stamina, xp FROM irc_qog WHERE nick = '"
						+ cmds[1] + "'";
				ResultSet rs;

				try {
					rs = dc.sendQuery(query);
					if (rs.next()) {
						if (rs.getString("CLASS").equals("agi")
								|| (rs.getString("CLASS").equals("str") || (rs
										.getString("CLASS").equals("int"))))
							sendMessage(channel, Colors.BOLD + cmds[1]
									+ Colors.BOLD + ": Level "
									+ rs.getInt("level") + " ("
									+ rs.getString("class") + ") [ "
									+ Colors.RED + "HP: " + Colors.NORMAL
									+ rs.getInt("HP") + " |" + Colors.BLUE
									+ " MP: " + Colors.NORMAL
									+ rs.getInt("mana") + " |" + Colors.PURPLE
									+ " Stamina: " + Colors.NORMAL + rs.getFloat("stamina")
									+ " |" + Colors.YELLOW + " XP: " + Colors.NORMAL
									+ rs.getInt("xp") + " ]");
						else
							sendMessage(channel, Colors.BOLD + cmds[1]
									+ Colors.BOLD + ": PURE NOOB!");
					}
					rs.close();
				} catch (EOFException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					// sendMessage(channel, cmds[1]+": 0.0");
					e.printStackTrace();
				}
			} else {

				String query = "select * from irc_qog where nick = '" + sender
						+ "'";
				ResultSet rs;

				try {
					rs = dc.sendQuery(query);

					if (rs.next())
						sendMessage(channel, Colors.BOLD + sender + Colors.BOLD + ": Level "
									+ rs.getInt("level") + " ("
									+ rs.getString("class") + ") [ "
									+ Colors.RED + "HP: " + Colors.NORMAL
									+ rs.getInt("HP") + " |" + Colors.BLUE
									+ " MP: " + Colors.NORMAL
									+ rs.getInt("mana") + " |" + Colors.PURPLE
									+ " Stamina: " + Colors.NORMAL + rs.getFloat("stamina")
									+ " |" + Colors.YELLOW + " XP: " + Colors.NORMAL
									+ rs.getInt("xp") + " ]");
					else
						sendMessage(channel, Colors.BOLD + sender + Colors.BOLD
								+ ": PURE NOOB!");
					rs.close();
				} catch (EOFException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		}
		// SMAJLY! :D
		else if (message.contains(":)") || message.contains(":]")
				|| message.contains(":>") || message.contains(":D")
				|| message.contains("=)") || message.contains("8)")
				|| message.contains("xD") || message.contains(":}")
				|| message.contains("^^") || message.contains("^_^")
				|| message.contains(":-)") || message.contains(":o)")
				|| message.contains("8-)") || message.contains(":-D")
				|| message.contains(";)") || message.contains(";-)")
				|| message.contains(";D") || message.contains("(:")
				|| message.contains("<:") || message.contains("haha")
				|| message.contains("HAHA") || message.contains("hehe")
				|| message.contains("HEHE") || message.contains("hihi")
				|| message.contains("HIHI") || message.contains("hoho")
				|| message.contains("HOHO")
				|| (message.contains("lo") && message.contains("ol"))
				|| message.contains("rofl") || message.contains("lmao")
				|| message.contains("xex")) {
			Random generator = new Random();

			if (generator.nextInt(100) > 80) {
				int i = generator.nextInt(20);
				String mes = "";
				switch (i) {
				case 0:
					mes = ":D";
					break;
				case 1:
					mes = ":F";
					break;
				case 2:
					mes = "to su mi smiechoty";
					break;
				case 3:
					mes = "no len sa tolko negeb";
					break;
				case 4:
					mes = "roflmao";
					break;
				case 5:
					mes = "skor tragikomicke";
					break;
				case 6:
					mes = ":p";
					break;
				case 7:
					mes = "stfu n00b :p";
					break;
				case 8:
					mes = "mvg!";
					break;
				case 9:
					mes = "you remind me of gay...";
					break;
				case 10:
					mes = "ke?";
					break;
				case 11:
					mes = ":)";
					break;
				case 12:
					mes = "x.x";
					break;
				case 13:
					mes = "len sa nepocikaj";
					break;
				case 14:
					mes = "dik, akurat jem...";
					break;
				case 15:
					mes = "do pohodicky typek";
					break;
				case 16:
					mes = "omgwtfbbqhax!";
					break;
				case 17:
					mes = "o.o";
					break;
				case 18:
					mes = "este nieco zadel";
					break;
				case 19:
					mes = "tam chod kodit!";
					break;
				default:
					mes = "bluglafnuf";
					break;
				}

				sendMessage(channel, mes);
			}
		} else if (message.contains(":(") || message.contains(":[")
				|| message.contains(":<") || message.contains(":{")
				|| message.contains("D:") || message.contains(":-(")
				|| message.contains(":o(") || message.contains(":\\")
				|| message.contains(">.<") || message.contains(">_<")
				|| message.contains("x.x") || message.contains("x_x")
				|| (message.contains(":_") && message.contains("_("))) {
			Random generator = new Random();

			if (generator.nextInt(100) > 80) {
				int i = generator.nextInt(8);
				String mes = "";
				switch (i) {
				case 0:
					mes = ":(";
					break;
				case 1:
					mes = "D:";
					break;
				case 2:
					mes = "este sa rozplacem";
					break;
				case 3:
					mes = ":_______(";
					break;
				case 4:
					mes = "to prejde, " + sender + "!!";
					break;
				case 5:
					mes = "hmm :<";
					break;
				case 6:
					mes = "to nastve";
					break;
				case 7:
					mes = "nebul!";
					break;
				default:
					mes = "bluglafnuf";
					break;
				}

				sendMessage(channel, mes);
			}
		}
		// na salata :>
		else if (message.toLowerCase().contains("shala")
				|| message.toLowerCase().contains("salat")) {
			Random generator = new Random();

			if (generator.nextInt(100) > 30) {
				int i = generator.nextInt(14);
				String mes = "";
				switch (i) {
				case 0:	mes = "no co zlato"; break;
				case 1:	mes = "zase ma ohovaraju salamovia"; break;
				case 2:	mes = "pritomen!"; break;
				case 3:	mes = "poslusne hlasim ze za mojej sluzby sa nic zvlastne nestalo, sudruh kapitan!"; break;
				case 4:	mes = "?"; break;
				case 5:	mes = "\\o/"; break;
				case 6:	mes = "neber meno bozie do tlamy nadarmo!"; break;
				case 7:
					mes = "lalala";
					break;
				case 8:
					mes = "ano ja viem ze som popularny";
					break;
				case 9:
					mes = "a poznate " + sender + ".istheshit.net/ ?";
					break;
				case 10:
					mes = "ale fakt mam rad (o)(o) :>";
					break;
				case 11:
					mes = "nic nebude!";
					break;
				case 12:
					mes = "ano?";
					break;
				case 13:
					mes = "hmm... nie";
					break;
				default:
					mes = "bluglafnuf";
					break;
				}

				sendMessage(channel, mes);
			}
		}
		// quotes!
		else if (message.startsWith("!quote")) {
			String[] cmds = message.split(" ");

			System.out.println(cmds[0]);

			if (cmds.length <= 1) {
				String query = "SELECT quote, user FROM irc_quotes";

				try {
					ResultSet rs = dc.sendQuery(query);

					ArrayList<String> ar = new ArrayList<String>();

					while (rs.next()) {
						String quota = rs.getString("quote");
						String usr = rs.getString("user");

						ar.add(Colors.BOLD + "quote: " + Colors.BOLD + quota
								+ " (c) " + usr);
					}
					rs.close();
					if (ar.size() > 0) {
						Random generator = new Random();

						sendMessage(channel, ar.get(generator
								.nextInt(ar.size())));
					} else
						sendMessage(channel, "nic tam neni luma!");
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (EOFException e) {
					System.err
							.println("[error] lost connection with DB, reconnecting");
					try {
						con = DriverManager
								.getConnection("jdbc:mysql://localhost/shalatikDB?user=shalatik&password=Hpp7fF2KySsK52DY");
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						System.out.println("[error] - can't reconnect");
					}
				}

			} else if (cmds.length > 1) {
				// String query =
				// "SELECT quote, user FROM irc_quotes WHERE MATCH (quote, user) AGAINST ('"+cmds[1]+"')";
				String query = "SELECT quote, user FROM irc_quotes WHERE quote LIKE '%"
						+ cmds[1] + "%' OR user LIKE '%" + cmds[1] + "%'";

				try {
					ResultSet rs = dc.sendQuery(query);

					ArrayList<String> ar = new ArrayList<String>();

					while (rs.next()) {
						String quota = rs.getString("quote");
						String usr = rs.getString("user");

						ar.add(Colors.BOLD + "quote: " + Colors.BOLD + quota
								+ " (c) " + usr);
					}
					rs.close();
					if (ar.size() > 0) {
						Random generator = new Random();

						sendMessage(channel, ar.get(generator
								.nextInt(ar.size())));
					} else
						sendMessage(channel, "nic tam neni luma!");
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (EOFException e) {
					System.err
							.println("[error] lost connection with DB, reconnecting");
					try {
						con = DriverManager
								.getConnection("jdbc:mysql://localhost/shalatikDB?user=shalatik&password=Hpp7fF2KySsK52DY");
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						System.out.println("[error] - can't reconnect");
					}
				}

			}

		} else if (message.startsWith("!addgreet ")) {
			String[] cmds = message.split(" ");

			if (cmds.length > 2) {
				String greet = "";

				for (int i = 1; i < cmds.length - 1; i++) {
					greet += cmds[i] + " ";
				}

				String usr = cmds[cmds.length - 1];

				// String query =
				// "SELECT greeting from irc_greetings where nick = '"+usr+"'";
				// try
				// {
				/*
				 * rs = dc.sendQuery(query);
				 * 
				 * rs.next(); try { rs.getString("greeting");
				 * sendMessage(channel, "ee ten/ta/to uz pozdrav ma :P"); }
				 * catch (SQLException ee) {
				 */
				greet = greet.replace("\\0", "");
				String query = "INSERT INTO irc_greetings VALUES (0, '" + greet
						+ "', '" + usr + "')";

				try {
					dc.sendUpdateQuery(query);
					sendMessage(channel, "ok pozdrav pridany :>");
				} catch (SQLException e) {
					e.printStackTrace();
					sendMessage(channel, "ech co to nejaka chyba o.O");
				}

				// }
				/*
				 * } catch (SQLException e) { e.printStackTrace(); } catch
				 * (EOFException e) {System.err.println(
				 * "[error] lost connection with DB, reconnecting"); try { con =
				 * DriverManager.getConnection(
				 * "jdbc:mysql://localhost:8889/shalatik?user=root&password=root"
				 * ); } catch (SQLException e1) { // TODO Auto-generated catch
				 * block System.out.println("[error] - can't reconnect"); } }
				 */
			}

		}
		// zobrazovanie qog
		else if (message.startsWith("!qog")) {
			String[] cmds = message.split(" ");

			if (cmds.length > 1) {

				String query = "select qog, level from irc_qog where nick = '"
						+ cmds[1] + "'";
				ResultSet rs;

				try {
					rs = dc.sendQuery(query);
					if (rs.next())
						sendMessage(channel, Colors.BOLD + cmds[1]
								+ Colors.BOLD + ": level " + rs.getInt("level")
								+ " qog " + rs.getFloat("qog"));
					else
						sendMessage(channel, Colors.BOLD + cmds[1]
								+ Colors.BOLD + ": level 1 qog 0.0");
					rs.close();
				} catch (EOFException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					// sendMessage(channel, cmds[1]+": 0.0");
					e.printStackTrace();
				}
			} else {

				String query = "select * from irc_qog where nick = '" + sender
						+ "'";
				ResultSet rs;

				try {
					rs = dc.sendQuery(query);

					if (rs.next())
						sendMessage(channel, Colors.BOLD + sender + Colors.BOLD
								+ ": level " + rs.getInt("level") + " qog "
								+ rs.getFloat("qog"));
					else
						sendMessage(channel, Colors.BOLD + sender + Colors.BOLD
								+ ": level 1 qog 0.0");
					rs.close();
				} catch (EOFException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		}

		/**
		 * QOG (Quality Of Gay) Calculator
		 */

		try {
			try {
				qogCalculator(sender, message);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		/*
		 * // ZVYSOVANIE if (message.toLowerCase().contains("harry potter"))
		 * updateQOG(sender, 1.0f);
		 * 
		 * if (message.toLowerCase().contains("preco")) updateQOG(sender, 0.3f);
		 * 
		 * if (message.toLowerCase().contains("balki")) updateQOG(sender, 0.2f);
		 * 
		 * if (message.toLowerCase().contains(" emo")) updateQOG(sender, 1.0f);
		 * 
		 * if (message.toLowerCase().contains("co je to") ||
		 * message.toLowerCase().contains("co to je") ||
		 * message.toLowerCase().contains("to co je") ||
		 * message.toLowerCase().contains("to je co")) updateQOG(sender, 1.0f);
		 * 
		 * if (message.toLowerCase().contains("ike ike")) updateQOG(sender,
		 * 0.1f);
		 * 
		 * if (message.toLowerCase().contains("tokio hotel")) updateQOG(sender,
		 * 1.5f);
		 * 
		 * if (message.toLowerCase().contains("anime")) updateQOG(sender, 0.7f);
		 * 
		 * if (message.toLowerCase().contains("teplos")) updateQOG(sender,
		 * 1.0f);
		 * 
		 * if (message.toLowerCase().contains("dance")) updateQOG(sender, 0.8f);
		 * 
		 * 
		 * // ZNIZOVANIE if (message.toLowerCase().contains("kokot"))
		 * updateQOG(sender, -0.5f);
		 * 
		 * if (message.toLowerCase().contains("kkt")) updateQOG(sender, -0.2f);
		 * 
		 * if (message.toLowerCase().contains("sex")) updateQOG(sender, -0.5f);
		 * 
		 * if (message.toLowerCase().contains("pron")) updateQOG(sender, -0.3f);
		 * 
		 * if (message.toLowerCase().contains("porn")) updateQOG(sender, -0.2f);
		 * 
		 * if (message.toLowerCase().contains("dota")) updateQOG(sender, -1.0f);
		 * 
		 * if (message.toLowerCase().contains("berry")) updateQOG(sender,
		 * -0.9f);
		 */

	}

	private void decreaseStamina(String sender, float amount)
	{
		try
		{
			String query = "UPDATE irc_qog SET stamina = GREATEST(stamina - " + amount + ", 0)"
			+ " WHERE nick = '" + sender + "'";

			System.out.println(query);
			dc.sendUpdateQuery(query);
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	public void onPrivateMessage(String sender, String login, String hostname,
			String message) {
		// SAY :>
		if (message.startsWith("!say ")) {
			String what = "";
			String[] spl = message.split(" ");

			for (int i = 1; i < spl.length; i++) {
				what += spl[i] + " ";
			}

			// TODO: posielanie zatial len na 1. channel kde je
			sendMessage(this.getChannels()[0], what);
		}

	}

	public void onJoin(String channel, String sender, String login,
			String hostname) {
		// seba nezdravim :P
		if (!sender.equals("shalatik")) {
			String query = "SELECT greeting from irc_greetings where nick = '"
					+ sender + "'";

			try {
				ArrayList<String> ar = new ArrayList<String>();
				ResultSet rs = dc.sendQuery(query);

				while (rs.next()) {
					String quota = rs.getString("greeting");

					ar.add(quota);
				}
				rs.close();
				if (ar.size() > 0) {
					Random generator = new Random();

					sendMessage(channel, ar.get(generator.nextInt(ar.size())));
				}

				// rs.next();
				// String greeting = rs.getString("greeting");
				// if ((greeting != null) && (!greeting.equals("")))
				// sendMessage(channel, greeting);
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (EOFException e) {
				System.err
						.println("[error] lost connection with DB, reconnecting");
				try {
					con = DriverManager
							.getConnection("jdbc:mysql://localhost/shalatikDB?user=shalatik&password=Hpp7fF2KySsK52DY");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					System.out.println("[error] - can't reconnect");
				}
			}

		}
	}

	public void onKick(String channel, String kickerNick, String kickerLogin,
			String kickerHostname, String recipientNick, String reason) {
		joinChannel(channel);
		sendMessage(channel, "omgwtf " + kickerNick + "!!!");
	}

	public Connection getCon() {
		return con;
	}

	public void setCon(Connection con) {
		this.con = con;
	}

}
